<template>
  <view class="content">
    <view class="top">
      <view class="left" @click="gotoDetail">
        <image :src="info.imgurl" mode=""></image>
      </view>
      <view class="center">
        <image src="../../static/images/index/logo.png" mode=""></image>
      </view>
      <view class="right">
        <image src="../../static/images/index/search.png" mode="" @click="gotoSearch"></image>
        <image src="../../static/images/index/add.png" mode="" @click="gotoCreateGroup"></image>
      </view>
    </view>
    <view class="firend" v-if="Object.keys(info.friendlist).length != 0">
      <view class="addfriend" @click="gotoAddFriends">
        <view class="apply">
          <image src="../../static/images/index/apply.png" mode=""></image>
          <view class="tip" v-if='info.reqLength != 0'>{{info.reqLength}}</view>
        </view>
        <view class="addfriend-right">
          <view class="addfriend-right-top">
            <span class="firendName">好友申请</span>
            <span class="time">{{formatDate(info.reqLastTime || new Date() )}}</span>
          </view>
          <view class="addfriend-right-bottom">
            <text>茫茫人海，相聚便是缘分</text>
          </view>
        </view>
      </view>

      <view class="firend-list" v-for="(item, index) in info.friendlist" :key="index" @click="gotoChat(item)">
        <view class="firend-list-left">
          <image :src="item.imgurl" mode=""></image>
          <view class="tip" v-if='item.tip != 0'>{{ item.tip }}</view>
          <view class="groupm" v-if="item.type"></view>
        </view>
        <view class="firend-list-right">
          <view class="firend-list-right-top">
            <span class="firendName" v-if='item.nickname != null'>{{ item.nickname }}</span>
            <span class="firendName" v-else>{{ item.username || item.groupname }}</span>
            <span class="time">{{ formatDate(item.lastTime) }}</span>
          </view>
          <view class="firend-list-right-bottom">
            <span>{{ item.msg }}</span>
          </view>
        </view>
      </view>
    </view>

    <!-- 下拉刷新 -->
    <view class="refresh" v-if="!info.refresh">
      <image src="../../static/images/index/refresh.png" mode=""></image>
      <view class="ref-fresh">下拉刷新</view>
    </view>
    <!-- 没有好友 -->
    <view class="noFriend" v-if='info.noOne'>
      <image src="../../static/images/index/noone.png" mode=""></image>
      <view class="no-title">你还没有好友</view>
      <button type="primary" size="mini" @click="gotoSearch">搜索好友</button>
    </view>

  </view>
</template>

<script setup>
  import {
    reactive,
    getCurrentInstance
  } from 'vue'
  import {
    onShow,
    onLoad,
    onPullDownRefresh
  } from '@dcloudio/uni-app'
  import {
    requestNet
  } from '@/api/base.js'
  import {
    useUserStore
  } from '@/store/user.js'
  import {
    formatDate
  } from '@/utils/formatDate.js'
  import {
    paixu
  } from '@/utils/utils.js'
  const instance = getCurrentInstance()
  const user = useUserStore() //创建仓库
  const info = reactive({
    token: '',
    userid: null, //当前用户id
    imgurl: '', //用户头像
    friendlist: [], //当前登录用户的好友 | 当前用户所加入的群
    grouplist: [], //当前用户所在的群
    reqLength: 0, //好友申请数
    reqLastTime: null, //最后申请时间
    refresh: false, //下拉刷新判断
    noOne: false, //没有人
    flag: true
  })

  onShow(() => {

  })

  onLoad(() => {
    getStorage()
    getFriendList()
    getGroup()
    getFriendReq()
    join(info.userid)
    receiveSocketMsg()
    groupSocket()
    leaveChat()
  })

  //socket模块 
  //用户登录socket注册
  function join(uid) {
    instance.proxy.socket.emit('login', uid)
  }

  //socket一对一聊天数据 || 群消息 接收
  function receiveSocketMsg() {
    instance.proxy.socket.on('msg', (msg, fromid) => {
      // console.log(msg, fromid)
      console.log('首页触发一对一消息接收')
      let nowmsg = ''
      if (msg.types == 0) {
        nowmsg = msg.message
      } else if (msg.types == 1) {
        nowmsg = '[图片]'
      } else if (msg.types == 2) {
        nowmsg = '[音频]'
      } else if (msg.types == 3) {
        nowmsg = '[位置]'
      }
      //对比对应项，然后修改
      for (let i = 0; i < info.friendlist.length; i++) {
        if (info.friendlist[i].id == fromid) { //匹配对应接收方用户
          let e = info.friendlist[i]
          e.lastTime = new Date()
          e.msg = nowmsg
          e.tip++
          //删除对应接收方用户原来的数据项
          info.friendlist.splice(i, 1)
          //新消息插入到最顶部  类型最新消息放最前
          info.friendlist.unshift(e)
        }
      }
    })
  }
  //群即时消息接收
  function groupSocket() {
    instance.proxy.socket.on('groupmsg', (msg, fromid, gid, name, avater) => {
      // console.log(msg, fromid, gid, name)
      console.log('首页触发群消息接收')
      let nowmsg = ''
      if (msg.types == 0) {
        nowmsg = msg.message
      } else if (msg.types == 1) {
        nowmsg = '[图片]'
      } else if (msg.types == 2) {
        nowmsg = '[音频]'
      } else if (msg.types == 3) {
        nowmsg = '[位置]'
      }
      //对比对应项，然后修改
      for (let i = 0; i < info.friendlist.length; i++) {
        if (info.friendlist[i].groupid == gid) { //匹配对应接收方用户
          let e = info.friendlist[i]
          e.lastTime = new Date()
          if (fromid == info.userid) {
            e.msg = nowmsg
          } else {
            e.msg = name + '：' + nowmsg
          }
          e.tip++
          //删除对应接收方用户原来的数据项
          info.friendlist.splice(i, 1)
          //新消息插入到最顶部  类型最新消息放最前
          info.friendlist.unshift(e)
        }
      }
    })
  }

  //离开当前聊天页面触发的socket
  function leaveChat() {
    instance.proxy.socket.on('leavechat', (uid, fid, flag) => {
      if (flag == 0) {
        //对比对应项，然后修改
        for (let i = 0; i < info.friendlist.length; i++) {
          if (info.friendlist[i].id == fid) { //匹配对应接收方用户
            let e = info.friendlist[i]
            e.tip = 0
            //替换对应接收方用户原来的数据项
            info.friendlist.splice(i, 1, e)
          }
        }
        //修改一对一聊天读取状态
        requestNet({
          url: "/home/upateMsg",
          method: 'POST',
          data: {
            uid: uid,
            fid: fid
          },
          header: {
            token: info.token
          }
        }).then(res => {}).catch(err => {
          console.log(err)
        })
      } else if (flag == 1) {
        //对比对应项，然后修改
        for (let i = 0; i < info.friendlist.length; i++) {
          if (info.friendlist[i].groupid == fid) { //匹配对应接收方用户
            let e = info.friendlist[i]
            e.tip = 0
            //替换对应接收方用户原来的数据项
            info.friendlist.splice(i, 1, e)
          }
        }
        //修改群聊天读取状态
        requestNet({
          url: "/home/updateGroupMsg",
          method: 'POST',
          data: {
            uid: uid,
            gid: fid
          },
          header: {
            token: info.token
          }
        }).then(res => {
          console.log(res)
        }).catch(err => {
          console.log(err)
        })
      }
    })
  }

  //前往好友申请页面
  function gotoAddFriends() {
    uni.navigateTo({
      url: '/pages/addfirend/addfirend?id=' + info.userid
    })
  }

  //获取好友用户数据
  function getFriendList() {
    requestNet({
      url: '/home/getUserList',
      data: {
        uid: info.userid,
        state: 0
      },
      header: {
        token: info.token
      }
    }).then(res => {
      let code = res.data.code
      if (code == 200) {
        info.refresh = true
        info.friendlist = res.data.data
        let temp = info.friendlist
        if (temp.length > 0) {
          info.noOne = false
          for (let i = 0; i < temp.length; i++) {
            if (!temp[i].imgurl.includes(instance.proxy.serverUrl)) { //不包含服务器地址
              info.friendlist[i].imgurl = `${instance.proxy.serverUrl}${temp[i].imgurl}`
            }
            info.friendlist[i].type = 0
          }
          isOk(info.grouplist)
        } else {
          info.noOne = true
        }
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //获取群列表
  function getGroup() {
    requestNet({
      url: '/home/getGroupList',
      data: {
        uid: info.userid,
      },
      header: {
        token: info.token
      }
    }).then(res => {
      let code = res.data.code
      if (code == 200) {
        let result = res.data.data
        if (result.length > 0) {
          for (let i = 0; i < result.length; i++) {
            result[i].type = 1
            result[i].imgurl = `${instance.proxy.serverUrl}${result[i].imgurl}`
            info.grouplist.push(result[i])
            //向socket服务端发送每个群的id 
            instance.proxy.socket.emit('group', result[i].groupid)
          }
          isOk(info.friendlist)
        }
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }


  //群与好友之间的排序
  function isOk(e) {
    if (e.length > 0) {
      //拼接数组
      info.friendlist = info.friendlist.concat(info.grouplist)
      info.friendlist = paixu(info.friendlist, 0)
    }
  }

  //获取申请好友的相关数据【请求数，时间】
  function getFriendReq() {
    requestNet({
      url: '/home/getUserList',
      data: {
        uid: info.userid,
        state: 1
      },
      header: {
        token: info.token
      }
    }).then(res => {
      // console.log(res)
      let code = res.data.code
      if (code == 200) {
        info.refresh = true
        let result = res.data.data
        info.reqLength = result.length
        if (result.length > 0) {
          //info.noOne = false
          info.reqLastTime = result[0].lastTime
          for (let i = 1; i < result.length; i++) {
            if (info.reqLastTime < result[i].lastTime)
              info.reqLastTime = result[i].lastTime
          }
        }
        // else {
        //   info.noOne = true
        // }
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //获取缓存数据
  function getStorage() {
    if (Object.keys(user.userinfo).length != 0) { //如果有数据，登录过了
      info.userid = user.userinfo.userid
      info.imgurl = user.userinfo.imgurl
      info.token = user.token
      if (!user.userinfo.imgurl.includes(instance.proxy.serverUrl)) { //不包含服务器地址
        info.imgurl = `${instance.proxy.serverUrl}${user.userinfo.imgurl}`
      }
    } else { //否则跳转到登录页面
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  }

  function gotoSearch() {
    uni.navigateTo({
      url: '/pages/search/search'
    })
  }

  function gotoCreateGroup() {
    uni.navigateTo({
      url: '/pages/buidGroup/buidGroup'
    })
  }

  function gotoDetail() {
    uni.navigateTo({
      url: `/pages/reqfirend/reqfirend?id=${info.userid}`
    })
  }

  //跳转到聊天页面
  function gotoChat(item) {
    console.log(item)
    if (item.type == 0) {
      if (item.nickname == null) {
        uni.navigateTo({
          url: `/pages/chatPage/chatPage?id=${item.id}&name=${item.username}&img=${item.imgurl}&type=${item.type}`
        })
      } else {
        uni.navigateTo({
          url: `/pages/chatPage/chatPage?id=${item.id}&name=${item.nickname}&img=${item.imgurl}&type=${item.type}`
        })
      }
    } else {
      uni.navigateTo({
        url: `/pages/chatPage/chatPage?id=${item.groupid}&name=${item.groupname}&img=${item.imgurl}&type=${item.type}`
      })
    }


  }


  onPullDownRefresh(() => {
    getFriendList()
    getFriendReq()
    setTimeout(function() {
      uni.stopPullDownRefresh();
    }, 1000);
  })
</script>

<style scoped lang="scss">
  @import '../../assets/css/top.scss';

  .content {

    .top {
      padding: 0 20rpx;
      border-bottom: 1px $uni-border-color solid;
      background-color: $uni-bg-color;
      position: fixed; //固定死，不占空间
      z-index: 999;
      left: 0;
      top: 0;
      height: 88rpx;
      width: 100%;

      .left {
        height: 68rpx;
        width: 68rpx;

        image {
          border-radius: 10px;
          height: 100%;
          width: 100%;
        }
      }

      .center {
        height: 42rpx;
        width: 88rpx;

        image {
          height: 100%;
          width: 100%;
        }
      }

      .right {
        display: flex;
        height: 52rpx;
        width: 120rpx;

        image {
          height: 100%;
          width: 100%;
          margin-right: 10rpx;
        }
      }
    }

    .firend {
      padding-top: 100rpx;

      .addfriend {
        padding: 0 0.625rem;
        display: flex;
        align-items: center;
        width: 100%;
        height: 4rem;
        border-bottom: 0.0625rem var(--border-color) solid;

        .apply {
          position: relative;
          background-color: #ffd607;
          border-radius: 10px;

          image {
            height: 3rem;
            width: 3rem;
          }

          .tip {
            position: absolute;
            top: -0.2rem;
            right: -0.4286rem;
            z-index: 100;
            padding: 0 8rpx;
            border-radius: 50%;
            color: var(--text-color-inverse);
            background-color: var(--color-warning);

          }

        }

        .addfriend-right {
          width: 100%;
          margin-left: 0.9375rem;

          .addfriend-right-top {
            display: flex;
            justify-content: space-between;

            .firendName {
              font-size: 32rpx;
            }

            .time {
              font-size: 24rpx;
              color: var(--text-color-grey);
            }
          }

          .addfriend-right-bottom {
            text {
              // 实现溢出显示省略号
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
              color: var(--text-color-grey);
              font-size: 24rpx;
            }
          }
        }
      }

      &-list {
        padding: 0 20rpx;
        display: flex;
        align-items: center;
        width: 100%;
        height: 128rpx;
        border-bottom: 2rpx var(--border-color) solid;

        &:active {
          background-color: var(--bg-color-hover);
        }

        &-left {
          position: relative;
          height: 96rpx;
          width: 96rpx;

          image {
            height: 96rpx;
            width: 96rpx;
            background-color: var(--bg-color);
            border-radius: 20rpx;
          }

          .tip {
            position: absolute;
            top: -0.4286rem;
            right: -0.4286rem;
            z-index: 100;
            padding: 0 8rpx;
            border-radius: 50%;
            color: var(--text-color-inverse);
            background-color: var(--color-warning);

          }

          .groupm {
            position: absolute;
            width: 16rpx;
            height: 16rpx;
            background-color: red;
            bottom: 0;
            right: -5rpx;
            border-radius: 10px;
          }
        }

        &-right {
          width: 100%;
          margin-left: 30rpx;

          &-top {
            display: flex;
            justify-content: space-between;

            .firendName {
              font-size: 32rpx;
            }

            .time {
              font-size: 24rpx;
              color: var(--text-color-grey);
            }
          }

          &-bottom {
            span {
              // 实现溢出显示省略号
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
              color: var(--text-color-grey);
              font-size: 24rpx;
            }
          }
        }

      }
    }

    .refresh {
      padding-top: 100rpx;
      text-align: center;


      image {
        width: 40rpx;
        height: 40rpx;
      }

      .ref-fresh {
        padding-top: 10rpx;
        font-size: 26rpx;
        color: var(--text-color-grey);
      }
    }

    .noFriend {
      padding-top: 300rpx;
      text-align: center;

      image {
        height: 250rpx;
        width: 150rpx;
      }

      .no-title {
        font-size: 26rpx;
        color: var(--text-color-grey);
        margin: 15rpx 0;
      }
    }
  }
</style>
